package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Project;
import com.kaishengit.entity.User;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.RowMapper;

public class ProjectDao {
	
	private DBHelp<Project> db=new DBHelp<Project>();
	
	public List<Project> showAllProject(){
		
		String sql="select id,name,description from t_project";
		
		return db.executeQueryToList(sql, new ProjectRowMapper());		
	}
	
	public Project findProjectById(int id){
		String sql = "select id,name,description from t_project where id = ?";
		return db.executeQueryToObject(sql, new ProjectRowMapper(), id);
		
	}
	
	public void save(Project project){
		
		String sql="insert into t_project(name,description) values(?,?)";
		db.executeSQL(sql, project.getName(),project.getDescription());
	}
	
	public void update(Project project){
		
		String sql="update t_project set name=?,description=?  from t_project where id=?";
		db.executeSQL(sql, project.getId());	
	}
	
	public void del(Project project){
		
		String sql="delete id,name,description form t_project where id=? ";
		db.executeSQL(sql, project.getId());
	}
	
	/*public	List<Project> findProjectByUserId(User user){
		String sql = "SELECT tp.id =? , NAME = ?, description = ?  FROM t_project AS tp LEFT JOIN t_project_member AS tpm ON tp.id = tpm.projectId WHERE userId = ?";
		
		List<Project> list = db.executeQueryToList(sql, new ProjectRowMapper(){

			public Project mapRow(ResultSet rs) throws SQLException {
				Project project = new Project();
				project.setId(rs.getInt("id"));
				project.setName(rs.getString("name"));
				project.setDescription(rs.getString("description"));
				
				return project;
			}
			
		}, user.getId());
		
		return list;
	}*/
	
	public List<Project> findProjectByUserId(User user) {
		String sql = "SELECT tp.id, name, description FROM t_project AS tp LEFT JOIN t_project_member AS tpm ON tp.id = tpm.projectId WHERE userId = ?";
		return db.executeQueryToList(sql, new ProjectRowMapper(), user.getId());
	}
	
	
	private class ProjectRowMapper implements RowMapper<Project> {

		public Project mapRow(ResultSet rs) throws SQLException {
			
			Project project=new Project();
			project.setId(rs.getInt("id"));
			project.setName(rs.getString("name"));
			project.setDescription(rs.getString("description"));
			
			return project;
		}
	}
	
}
